package cvi.com.reader.fragment;

import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.orhanobut.hawk.Hawk;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadmoreListener;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;
import cvi.com.reader.R;
import cvi.com.reader.activity.LiteraryMasterActivity;
import cvi.com.reader.activity.PersonalActivity;
import cvi.com.reader.adapter.LiteraryMasterAdapter;
import cvi.com.reader.base.BaseFragment;
import cvi.com.reader.bean.CategoriesBean;
import cvi.com.reader.bean.LiteraryMasterBean;
import cvi.com.reader.network.DefaultObserver;
import cvi.com.reader.network.NetWorkManager;
import cvi.com.reader.tool.UtilsOnclickListen;
import cvi.com.reader.tool.refresh.CustomRefreshFooter;
import cvi.com.reader.tool.refresh.CustomRefreshHeader;
import cvi.com.reader.widgets.MultiStateView;
import cvi.com.reader.widgets.MyGridView;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;

/**
 * Created by 梅涛 on 2020/7/22.
 * <p>
 * 文学巨匠fragment_literary_master
 */

public class LiteraryMasterFragment extends BaseFragment implements View.OnClickListener {

    @BindView(R.id.fragment_name)
    TextView fragmentName;
    @BindView(R.id.user_info)
    LinearLayout userInfo;
    @BindView(R.id.gridview)
    MyGridView gridview;
    Unbinder unbinder;
    @BindView(R.id.stateView)
    MultiStateView stateView;
    @BindView(R.id.smartRefreshLayout_home)
    SmartRefreshLayout smartRefreshLayout;
    private LiteraryMasterAdapter literaryMasterAdapter = null;
    //诗词大会，首页，课本，绘本，文学巨匠
    private List<CategoriesBean.RowsBean> rowsBeanList = new ArrayList<CategoriesBean.RowsBean>();
    private int has_children = -1;
    private int pid = -1;
    //首页宫格数据包含热门数据
    private List<LiteraryMasterBean.RowsBean> homeList = new ArrayList<LiteraryMasterBean.RowsBean>();

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_literary_master;
    }

    @Override
    protected boolean isBindEventBus() {
        return false;
    }

    @Override
    protected void initData() {
        //绑定生命周期,获取宫格数据
        NetWorkManager.getInstance().getNetWorkApiService().getLiteraryMasterData(pid).compose(this.<JSONObject>bindToLifecycle())
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new DefaultObserver<JSONObject>(getActivity()) {
                    @Override
                    protected void onSuccess(JSONObject response) {
                        getData(response);
                        smartRefreshLayout.finishRefresh(true);
                        stateView.setViewState(MultiStateView.VIEW_STATE_CONTENT);
                    }
                });


    }

    @Override
    protected void initView() {
        initSmartRefreshLayout();//下拉刷新
        stateView.getBackground().setAlpha(153);
        fragmentName.setText("文学巨匠");
        if (Hawk.contains("categoriesBeanList")) {
            rowsBeanList = Hawk.get("categoriesBeanList");
        }
        if (rowsBeanList != null) {
            for (int i = 0; i < rowsBeanList.size(); i++) {
                if ("文学巨匠".equals(rowsBeanList.get(i).getName())) {
                    pid = rowsBeanList.get(i).getId();
                    has_children = rowsBeanList.get(i).getHas_children();


                }
            }
        }
        userInfo.setOnClickListener(this);
    }

    private void getData(JSONObject response) {
        JSONArray array = response.getJSONArray("rows");
        for (int i = 0; i < array.size(); i++) {
            JSONObject object = (JSONObject) array.get(i);     //将array中的数据进行逐条转换
            LiteraryMasterBean.RowsBean rowsBean = (LiteraryMasterBean.RowsBean) JSONObject.toJavaObject(object, LiteraryMasterBean.RowsBean.class);  //通过JSONObject.toBean()方法进行对象间的转换
            homeList.add(rowsBean);
        }
        Log.d("sdsds", homeList.size() + "");
        if (homeList != null) {
            literaryMasterAdapter = new LiteraryMasterAdapter(getActivity(), homeList);
            gridview.setAdapter(literaryMasterAdapter);
            literaryMasterAdapter.notifyDataSetChanged();
            gridview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                    LiteraryMasterBean.RowsBean rowsBean = (LiteraryMasterBean.RowsBean) adapterView.getAdapter().getItem(i);
                    Bundle bundle = new Bundle();
                    bundle.putInt("grid_id", rowsBean.getId());
                    bundle.putString("grid_name", rowsBean.getName());
                    go(LiteraryMasterActivity.class, bundle);

                }
            });
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // TODO: inflate a fragment view
        View rootView = super.onCreateView(inflater, container, savedInstanceState);
        unbinder = ButterKnife.bind(this, rootView);
        return rootView;
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.user_info:
                if (UtilsOnclickListen.isFastClick()) {
                    go(PersonalActivity.class);
                }
                break;
        }
    }

    //初始化下拉刷新控件
    private void initSmartRefreshLayout() {
        smartRefreshLayout.setEnableLoadmore(false);
        smartRefreshLayout.setRefreshHeader(new CustomRefreshHeader(getActivity()));
        smartRefreshLayout.setRefreshFooter(new CustomRefreshFooter(getActivity(), "加载中…"));
        smartRefreshLayout.setEnableScrollContentWhenLoaded(true);//是否在加载完成时滚动列表显示新的内容
        smartRefreshLayout.setEnableFooterFollowWhenLoadFinished(true);
        smartRefreshLayout.setOnRefreshLoadmoreListener(new OnRefreshLoadmoreListener() {
            @Override
            public void onLoadmore(RefreshLayout refreshlayout) {
                //  presenter.onLoadMore();
            }

            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                homeList.clear();
                initData();
            }
        });

    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }
}
